package com.study.spaoplog;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.zeroturnaround.exec.ProcessExecutor;
import org.zeroturnaround.exec.ProcessResult;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.*;

/**
 * @author study
 * @version 1.0
 * @date 2021/6/29 10:07
 */
@Slf4j(topic = "exec")
public class ExecDemo {
    @Test
    public void exec01() throws IOException, InterruptedException, TimeoutException {
        new ProcessExecutor().command("java", "-version").execute();

    }

    @Test
    public void execReturnUTF8() throws IOException, InterruptedException, TimeoutException {
        String output = new ProcessExecutor().command("ping", "127.0.0.1")
                .readOutput(true).execute()
                .outputUTF8();
        System.out.println(output);

    }

    @Test
    public void execOutputStream() throws IOException, InterruptedException, TimeoutException {
        OutputStream out = new PrintStream(System.out);
        new ProcessExecutor().command("java", "-version")
                .redirectOutput(out).execute();

    }

    @Test
    public void execBackGround() throws IOException, ExecutionException, InterruptedException, TimeoutException {
        Future<ProcessResult> future = new ProcessExecutor()
                .command("ping", "127.0.0.1", "-t")
                .readOutput(true)
                .start().getFuture();
        // do some stuff
        String output = future.get(60, TimeUnit.SECONDS).outputUTF8();
        System.out.println(output);

    }

    @Test
    public void execBackSou() throws IOException, InterruptedException {
        OutputStream out = new PrintStream(System.out);
        final Future<ProcessResult> ping = new ProcessExecutor()
                .command("ping", "127.0.0.1", "-t")
                .redirectOutput(out)
                .start().getFuture();

        int num = 0;
        while (true) {
            log.info("{}", ping.isDone());
            try {
                TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            num++;
            if (num > 12) {
                ping.cancel(true);
                return;
            }
        }
    }
}
